package com.example.mq.mqclient;

import com.example.mq.common.*;

import java.io.*;
import java.net.Socket;
import java.net.SocketException;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Connection {
    private Socket socket=null;
    private ConcurrentHashMap<String,Channel> channelMap=new ConcurrentHashMap<>();

    private InputStream inputStream;
    private OutputStream outputStream;
    private DataInputStream dataInputStream;
    private DataOutputStream dataOutputStream;
    private ExecutorService callbackPool=null;

    public Connection(String host,int port) throws IOException {
        socket=new Socket(host,port);
        inputStream=socket.getInputStream();
        outputStream=socket.getOutputStream();
        dataInputStream=new DataInputStream(inputStream);
        dataOutputStream=new DataOutputStream(outputStream);
        callbackPool= Executors.newFixedThreadPool(4);

        Thread t=new Thread(()->{
           try {
               while (!socket.isClosed()){
                   Response response=readResponse();
                   dispatchResponse(response);
               }
           }catch (SocketException e){
               System.out.println("[Connection] 连接正常断开！");
           }catch (IOException|ClassNotFoundException|MqException e){
               System.out.println("[Connection] 连接异常断开！");
               e.printStackTrace();
           }
        });
        t.start();
    }

    public void close(){
        try {
            callbackPool.shutdownNow();
            channelMap.clear();
            inputStream.close();
            outputStream.close();
            socket.close();
        }catch (IOException e){
            e.printStackTrace();
        }
    }

    private void dispatchResponse(Response response) throws IOException, ClassNotFoundException, MqException {
        if(response.getType()==0xc){
            SubScribeReturns subScribeReturns= (SubScribeReturns) BinaryTool.fromBytes(response.getPayload());
            Channel channel=channelMap.get(subScribeReturns.getChannelId());
            if(channel==null){
                throw new MqException("[Connection] 该消息对应的channel在客户端中不存在，channelId="+channel.getChannelId());
            }
            callbackPool.submit(()->{
               try {
                   channel.getConsumer().handleDelivery(subScribeReturns.getConsumerTag(),subScribeReturns.getBasicProperties(),subScribeReturns.getBody());
               }catch (MqException|IOException e){
                   e.printStackTrace();
               }
            });
        }else{
            BasicReturns basicReturns= (BasicReturns) BinaryTool.fromBytes(response.getPayload());
            Channel channel=channelMap.get(basicReturns.getChannelId());
            if(channel==null){
                throw new MqException("[Connection] 该消息对应的channel在客户端中不存在！channelId="+channel.getChannelId());
            }
            channel.putReturns(basicReturns);
        }
    }

    public void writeRequest(Request request) throws IOException {
        dataOutputStream.writeInt(request.getType());
        dataOutputStream.writeInt(request.getLength());
        dataOutputStream.write(request.getPayload());
        dataOutputStream.flush();
        System.out.println("[Connection] 发送请求！type="+request.getType()+",length="+request.getLength());
    }

    public Response readResponse() throws IOException {
        Response response=new Response();
        response.setType(dataInputStream.readInt());
        response.setLength(dataInputStream.readInt());
        byte[] payload=new byte[response.getLength()];
        int n=dataInputStream.read(payload);
        if(n!=response.getLength()){
            throw new IOException("读取的响应数据不完整");
        }
        response.setPayload(payload);
        System.out.println("[Connection] 收到响应！type="+response.getType()+",length="+response.getLength());
        return response;
    }

    public Channel createChannel() throws IOException {
        String channelId="C-"+ UUID.randomUUID().toString();
        Channel channel=new Channel(channelId,this);
        channelMap.put(channelId,channel);
        boolean ok=channel.createChannel();
        if(!ok){
            channelMap.remove(channelId);
            return null;
        }
        return channel;
    }
}
